import base64
import time
import requests


# author：CSDN-Dragon少年
def get_token():
    client_id = 'KQeKUl18OW06PFfiqhz5tUlL'
    client_secret = '7ZAFUc79xxOYVCYuL4PHmbcs6E9D9t4G'
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    response = requests.get(host)
    if response:
        token_info = response.json()
        token_key = token_info['access_token']
    return token_key

# author：CSDN-Dragon少年
def get_license_plate(car_pic):
    result = {}
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate"
    # 二进制方式打开图片文件
    f = open(car_pic, 'rb')
    img = base64.b64encode(f.read())
    params = {"image": img}
    access_token = get_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        # print(response.json())
        try:
            license_result = response.json()['words_result']['number']
            card_color = response.json()['words_result']['color']
            if license_result != []:
                result['InputTime'] = time.strftime("%Y-%m-%d %H:%M:%S")
                result['Number'] = ''.join(license_result[:2]) + '·' + ''.join(license_result[2:])
                return result
        except:
            return "None"
    else:
        return "None"

